package com.webapps.tvprogram.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.SimpleAdapter.ViewBinder;

import com.webapps.tvprogram.R;
import com.webapps.tvprogram.data.local.Program;
import com.webapps.tvprogram.data.local.ProgramItem;

public class AllProgramsListWithIconActivity extends Activity {

    private List<Map<String, Object>> list;
    private SimpleAdapter adapter;
    private static final String ICON = "icon";
    private static final String NAME = "name";
    private static final String CONTENT = "content";
    private static final String[] PARAM = {ICON, NAME, CONTENT};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        list = new ArrayList<Map<String, Object>>();
        setContentView(R.layout.program_list_view_all);
        List<Program> l = MainActivity.getInstance().getProgramsData();
        for (Iterator<Program> iterator = l.iterator(); iterator.hasNext();) {
            Program p = iterator.next();
            List<ProgramItem> l2 = p.getProgramItems();
            for (Iterator<ProgramItem> iterator2 = l2.iterator(); iterator2.hasNext();) {
                ProgramItem pi = iterator2.next();
                addItem(list, p.getIcon(), p.getName(), ">> " + pi.getName() + ", start: " + pi.getStartTime());
            }
        }
        adapter = new SimpleAdapter(this, list, R.layout.list_icon_2text_elem, PARAM, new int[]{R.id.list_icon, R.id.list_title,
                R.id.list_content});
        adapter.setViewBinder(new MyViewBinder());
        TextView tv = (TextView) findViewById(R.id.programs_list_all_header);
        tv.setText(R.string.all_programs_list_header);
        ListView lv = (ListView) findViewById(R.id.programs_list_all);
        lv.setAdapter(adapter);
    }

    private void addItem(List<Map<String, Object>> data, Bitmap bitmap, String name, String content) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(ICON, bitmap);
        map.put(NAME, name);
        map.put(CONTENT, content);
        data.add(map);
    }
}

class MyViewBinder implements ViewBinder {

    @Override
    public boolean setViewValue(View view, Object data, String textRepresentation) {
        if ((view instanceof ImageView) && (data instanceof Bitmap)) {
            ImageView iv = (ImageView) view;
            Bitmap bm = (Bitmap) data;
            iv.setImageBitmap(bm);
            return true;
        }
        return false;
    }
}
